<template>
  <Teleport to="#tooltip">
    <Transition name="fadeScale">
      <div class="tooltip" :style="{ inset: location }" ref="tooltipRef" v-show="visible">
        <div class="tooltip-title">{{ title }}</div>
        <div class="tooltip-arrow"></div>
      </div>
    </Transition>
  </Teleport>
  <div class="tooltip" ref="tooltipRefVisible" style="z-index: -100; position: absolute; visibility: hidden;">
    <div class="tooltip-title">{{ title }}</div>
    <div class="tooltip-arrow"></div>
  </div>
  <div ref="slotContent" @mouseenter="confirmLocation" @mouseleave="cancel">
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { defineProps, ref, Teleport, onMounted, nextTick } from 'vue'
const props = defineProps({
  title: {
    type: String
  }
})

const slotContent = ref<HTMLDivElement | null>(null)
const tooltipRef = ref<HTMLDivElement | null>(null)
const tooltipRefVisible = ref<HTMLDivElement | null>(null)

const location = ref('0 0 0 0')
const visible = ref(false)

// 确定tooltip位置
const confirmLocation = () => {
  nextTick(() => {
    const { top = 0, right = 0, bottom, left = 0, width: slotWidth = 0, height: slotHeight = 0 } =
      slotContent.value?.children[0]?.getBoundingClientRect() || {}
    const { width: tooltipWidth, height: tooltipHeight } = tooltipRefVisible.value?.getBoundingClientRect() || { width: 0, height: 0 }
    console.log(tooltipWidth, tooltipHeight)
    location.value = `${top - slotHeight / 2 - tooltipHeight}px ${right}px ${bottom}px ${left - tooltipWidth / 2 + slotWidth / 2}px`
    visible.value = true
  })
}

// 隐藏tooltip
const cancel = () => {
  visible.value = false
}
</script>

<style lang="scss" scoped>
@import './style.scss';
@import '../../css/comment/animate.css';
</style>
